import * as winston from 'winston';
import { loadEnvConfig } from '../config/loadEnv.config';
import { EnvEnum } from '../enums/env.enum';
import { utilities, WinstonModule } from 'nest-winston';
import { Console } from 'winston/lib/winston/transports';
import 'winston-daily-rotate-file';

function createDailyRotateTransport(level: string, filename: string) {
  return new winston.transports.DailyRotateFile({
    level,
    dirname: 'logs', //日志文件夹
    filename: `${filename}-%DATE%.log`, //日志名称，占位符 %DATE% 取值为 datePattern 值
    datePattern: 'YYYY-MM-DD', //日志轮换的频率，此处表示每天。其他值还有：YYYY-MM、YYYY-MM-DD-HH、YYYY-MM-DD-HH-mm
    zippedArchive: true, //是否通过压缩的方式归档被轮换的日志文件
    maxSize: '20m', // 设置日志文件的最大大小，m 表示 mb 。
    maxFiles: '14d', // 保留日志文件的最大天数，此处表示自动删除超过 14 天的日志文件
    format: winston.format.combine(
      winston.format.timestamp({
        format: 'YYYY-MM-DD HH:mm:ss',
      }),
      winston.format.simple(),
    ),
  });
}

export const setupLogger = () => {
  const config = loadEnvConfig();
  const timestamp = config[EnvEnum.TIMESTAMP] === 'true';
  const combine = [];
  if (timestamp) {
    combine.push(winston.format.timestamp());
  }
  combine.push(utilities.format.nestLike());
  const consoleTransports = new Console({
    level: (config[EnvEnum.LOG_LEVEL] as string) || 'info',
    format: winston.format.combine(...combine),
  });
  const otherTransports =
    config[EnvEnum.LOG_ON] === 'true'
      ? [
        createDailyRotateTransport('info', 'application'),
        createDailyRotateTransport('warn', 'error'),
      ]
      : [];

  return WinstonModule.createLogger({
    transports: [consoleTransports, ...otherTransports],
  });
};
